<?php

namespace app\admin\logic;

use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Service\MenuService;

class MenuLogic extends BackendLogic
{

    public function __construct()
    {
        $this->service=Container::get(MenuService::class);
    }

    protected static array $checked_config = [
        'index' => '查询',
        'add' => '添加',
        'edit' => '修改',
        'delete' => '删除',
        'info' => '详情',
        'status' => '状态',
        'dall' => '批量删除',
    ];

    /**
     * 菜单列表
     * @return array
     * @author 白鹄
     * @since 2024/01/01
     */
    public  function getList(): array
    {
        // 请求参数
        $param = request()->get();
        $where[] = ['mark', '=', 1];
        //菜单标题
        if (!empty($param['name'])) $where[] = ["title", 'like', "%{$param['name']}%"];
        $list = $this->service->getList($where, ['*'], ['sort' => 'asc']);
        $list = createTreeList(0, $list);
        return message($list);
    }

    /**
     * 获取菜单信息
     * @return array
     */
    public  function getInfo(): array
    {
        $param = request()->get();
        if (empty($param['id'])) return message();
        $id = $param['id'];
        $where[] = ['mark', '=', 1];
        $where[] = ['id', '=', $id];
        $info =  $this->service->getInfoByWhere($where);

        if ($info['type'] != 0) return message($info);
        $checkedList = [];
        $permissionList =  $this->service->getList([["pid", "=", $info['id']], ["type", "=", 1], ["mark", "=", 1]], ['permission']);
        if (is_array($permissionList)) {
            foreach ($permissionList as $v) {
                $permission = explode(":", $v['permission']);
                $checkedList[] = $permission[count($permission) - 1];
            }
        }
        $info['checkedList'] = $checkedList;
        return message($info);
    }

    /**
     * 获取权限列表
     * @param int $userId 用户ID
     * @return
     * @since 2020/11/19
     */
    public  function getPermissionList(int $userId): array
    {
        new self();
        if ($userId == 1) {
            // 管理员拥有全部权限
            $list =  $this->service->getChilds(0);
        } else {
            // 其他角色
            $list =  $this->service->getPermissionMenu($userId, 0);
        }
        return message($list);
    }

    /**
     * 编辑菜单
     * @return array
     */
    public  function edit()
    {
        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (empty($data['title'])) throw new ApiException('请输入菜单名称');
        if (empty($data['sort'])) throw new ApiException('请输入排序');
        $save['title'] = trim($data['title']);
        $save['sort'] = $data['sort'];
        $save['component'] = $data['component'] ?? '';
        $save['hide'] = $data['hide'] ?? 0;
        $save['icon'] = $data['icon'] ?? '';
        $save['pid'] = $data['pid'] ?? 0;
        $save['path'] = $data['path'] ?? '';
        $save['status'] = $data['status'] ?? 1;
        $save['target'] = $data['target'] ?? '_self';
        $save['type'] = $data['type'] ?? 0;
        $save['permission'] = $data['permission'] ?? '';
        unset($data['id']);
        if ($id == 0) {
            $res = $this->service->add($save);
        } else {
            $this->service->save($save, $id);
            $res = $id;
        }
        if (!$res) throw new ApiException('操作失败');
        $checkedList = $data['checkedList'] ?? [];
        if ($data['type'] == 1 && !empty($data['path']) && !empty($checkedList)) {
            $path = explode("/", $data['path']);
            // 模块名称
            $moduleName = $path[count($path) - 1];
            foreach ($checkedList as $item) {
                if (!in_array($item, array_keys(self::$checked_config))) continue;
                $rule_data = [];
                $rule_data['pid'] = $res;
                $rule_data['type'] = 3;
                $rule_data['sort'] = 1;
                $rule_data['target'] = '_self';
                $rule_data['title'] = self::$checked_config[$item];
                $rule_data['permission'] = "sys:{$moduleName}:" . $item;
                // 判断当前节点是否已存在
                $permission_info =  $this->service->getInfoByWhere([
                    ['pid', '=', $res],
                    ['type', '=', 1],
                    ['mark', '=', 1],
                    ['permission', '=', $rule_data['permission']],
                ]);
                if ($permission_info) continue;
                $this->service->add($rule_data);
            }
        }
        return message();

    }

    /**
     * 隐藏 菜单
     * @return array
     */
    public  function hide(): array
    {
        $id = request()->post('id');
        $status = request()->post('hide');
        if (!$id) throw new ApiException('记录ID不能为空');
        if (!in_array($status, [0, 1])) throw new ApiException('类型错误');
        $this->service->save(['hide' => $status], $id);
        return message();
    }


}
